package com.example.videotest;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.MediaController;
import android.widget.VideoView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends Activity {

    private static final String LATEST_VIDEO_URL_ENDPOINT = "http://192.168.1.228:8089/product/file/latest-video-url";
    private static final long POLL_INTERVAL = 10 * 1000; // 10 seconds
    private static final String TAG = "MainActivity";
    public static String latestVideoUrl = null;
    private VideoView videoView;
    private Handler handler;
    private OkHttpClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        videoView = findViewById(R.id.videoView);
        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        videoView.setMediaController(mediaController);

        handler = new Handler();
        client = new OkHttpClient();

        startPolling();
    }

    private void startPolling() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                fetchLatestVideoUrl();
                handler.postDelayed(this, POLL_INTERVAL);
            }
        }, POLL_INTERVAL);
    }

    private void fetchLatestVideoUrl() {
        Request request = new Request.Builder()
                .url(LATEST_VIDEO_URL_ENDPOINT)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "Failed to fetch latest video URL", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    Log.e(TAG, "Unexpected code " + response);
                    return;
                }

                String responseBody = response.body().string();

                // 使用Gson解析响应体
                Gson gson = new Gson();
                JsonObject jsonObject = gson.fromJson(responseBody, JsonObject.class);

                if (jsonObject.has("code") && jsonObject.get("code").getAsInt() == 1) {
                    latestVideoUrl = jsonObject.get("data").getAsString();
                    Log.d(TAG, "图片的访问路径: " + latestVideoUrl);
                } else {
                    String errorMsg = jsonObject.has("msg") ? jsonObject.get("msg").getAsString() : "未知错误";
                    Log.e(TAG, "上传失败，错误信息: " + errorMsg);
                }

                runOnUiThread(() -> playVideo(latestVideoUrl));
            }
        });
    }

    private void playVideo(String videoUrl) {
        if (videoUrl != null && !videoUrl.isEmpty()) {
            Log.d(TAG, "Playing video: " + videoUrl);
            videoView.setVideoPath(videoUrl);
            videoView.setOnPreparedListener(mp -> videoView.start());
            videoView.setOnErrorListener((mp, what, extra) -> {
                Log.e(TAG, "Error playing video. What: " + what + " Extra: " + extra);
                return true;
            });
        } else {
            Log.e(TAG, "Video URL is null or empty.");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
